import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class BillManager {
    private List<Transaction> incomeTransactions = new ArrayList<>();// 存储收入记录
    private List<Transaction> expenseTransactions = new ArrayList<>(); // 存储支出记录
    private double monthlyBudget;//每月预算
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private Scanner scanner; // 添加scanner为成员变量

    public BillManager(Scanner scanner) {
        this.scanner = scanner;
    }
    public void recordIncome() {
        System.out.print("请输入日期（YYYY-MM-DD）："+"\n");
        String dateStr = scanner.nextLine();
        System.out.print("请输入金额："+"\n");
        double amount = scanner.nextDouble();
        scanner.nextLine();
        System.out.print("请输入类别："+"\n");
        String category = scanner.nextLine();
        System.out.print("请输入备注："+"\n");
        String remark = scanner.nextLine();

        try {
            LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER);
            incomeTransactions.add(new Transaction(date, amount, category, remark));
            System.out.println("收入已成功记录！"+"\n");
        } catch (DateTimeParseException e) {
            System.out.println("日期格式错误，正确格式应为：yyyy-MM-dd"+"\n");
        }
    }

    public void recordExpense() {
        System.out.print("请输入日期（YYYY-MM-DD）："+"\n");
        String dateStr = scanner.nextLine();
        System.out.print("请输入金额："+"\n");
        double amount = scanner.nextDouble();
        scanner.nextLine();
        System.out.print("请输入类别："+"\n");
        String category = scanner.nextLine();
        System.out.print("请输入备注："+"\n");
        String remark = scanner.nextLine();

        try {
            LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER);
            expenseTransactions.add(new Transaction(date, amount, category, remark));
            System.out.println("支出已成功记录！"+"\n");
        } catch (DateTimeParseException e) {
            System.out.println("日期格式错误，正确格式应为：yyyy-MM-dd"+"\n");
        }
    }

    private void recordTransaction() {
        System.out.print("请输入日期（YYYY-MM-DD）："+"\n");
        String dateStr = scanner.nextLine();
        System.out.print("请输入金额："+"\n");
        double amount = scanner.nextDouble();
        scanner.nextLine();
        System.out.print("请输入类别："+"\n");
        String category = scanner.nextLine();
        System.out.print("请输入备注："+"\n");
        String remark = scanner.nextLine();

        try {
            LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER);
            expenseTransactions.add(new Transaction(date, amount, category, remark));
            System.out.println("支出已成功记录！"+"\n");
        } catch (DateTimeParseException e) {
            System.out.println("日期格式错误，正确格式应为：yyyy-MM-dd"+"\n");
        }
    }
    public void displayTransactions() {
        System.out.println("\n收入记录：");
        incomeTransactions.forEach(System.out::println);
        System.out.println("\n支出记录：");
        expenseTransactions.forEach(System.out::println);
    }

    public void queryTransactions() {   //处理用户的各种账单查询请求
        System.out.print("请输入查询类型（1：按日期，2：按类别，3：按日期范围）："+"\n");
        int type = scanner.nextInt();
        scanner.nextLine();

        switch (type) {
            case 1:
                System.out.print("请输入查询日期(YYYY-MM-DD):"+"\n");
                String dateStr = scanner.nextLine();
                try {
                    LocalDate date = LocalDate.parse(dateStr, DATE_FORMATTER);
                    List<Transaction> filteredTransactions = incomeTransactions.stream()
                            .filter(transaction -> transaction.getDate().isEqual(date))
                            .collect(Collectors.toList());
                    filteredTransactions.addAll(expenseTransactions.stream()
                            .filter(transaction -> transaction.getDate().isEqual(date))
                            .collect(Collectors.toList()));
                    filteredTransactions.forEach(System.out::println);
                } catch (DateTimeParseException e) {
                    System.out.println("日期格式错误，正确格式应为：yyyy-MM-dd"+"\n");
                }
                break;
            case 2:
                System.out.print("请输入类别："+"\n");
                String category = scanner.nextLine();
                List<Transaction> filteredTransactions = incomeTransactions.stream()
                        .filter(transaction -> transaction.getCategory().equals(category))
                        .collect(Collectors.toList());
                filteredTransactions.addAll(expenseTransactions.stream()
                        .filter(transaction -> transaction.getCategory().equals(category))
                        .collect(Collectors.toList()));
                if (filteredTransactions.isEmpty()) {
                    System.out.println("没有找到该类别的交易记录。"+"\n");
                } else {
                    filteredTransactions.forEach(System.out::println);
                }
                break;
            case 3:
                System.out.print("请输入开始日期(YYYY-MM-DD):"+"\n");
                String startDateStr = scanner.nextLine();
                System.out.print("请输入结束日期(YYYY-MM-DD):"+"\n");
                String endDateStr = scanner.nextLine();
                try {
                    LocalDate startDate = LocalDate.parse(startDateStr, DATE_FORMATTER);
                    LocalDate endDate = LocalDate.parse(endDateStr, DATE_FORMATTER);
                    queryByDateRange(startDate, endDate);
                } catch (DateTimeParseException e) {
                    System.out.println("日期格式错误，正确格式应为：yyyy-MM-dd"+"\n");
                }
                break;
            default:
                System.out.println("无效的查询类型。"+"\n");
                break;
        }
    }
    private void queryByCategory(String category) {
        List<Transaction> filteredTransactions = incomeTransactions.stream()
                .filter(transaction -> transaction.getCategory().equals(category))
                .collect(Collectors.toList());
        filteredTransactions.addAll(expenseTransactions.stream()
                .filter(transaction -> transaction.getCategory().equals(category))
                .collect(Collectors.toList()));
        filteredTransactions.forEach(System.out::println);
    }
    private void queryByDateRange(LocalDate startDate, LocalDate endDate) {
        List<Transaction> filteredTransactions = incomeTransactions.stream()
                .filter(transaction -> transaction.getDate().isAfter(startDate) && transaction.getDate().isBefore(endDate))
                .collect(Collectors.toList());
        filteredTransactions.addAll(expenseTransactions.stream()
                .filter(transaction -> transaction.getDate().isAfter(startDate) && transaction.getDate().isBefore(endDate))
                .collect(Collectors.toList()));
        filteredTransactions.forEach(System.out::println);
    }
    public void setMonthlyBudget(){
        System.out.print("请输入月度预算: "+"\n");
        double budget = scanner.nextDouble();
        this.monthlyBudget = budget;
        System.out.println("月度预算已经设置为："+budget);
    }
    public double getMonthlyBudget(){
        double totalExpense = expenseTransactions.stream().mapToDouble(Transaction::getAmount).sum();
        return monthlyBudget - totalExpense;
    }
    public void displayRemainingBudget(){
        System.out.println("当前剩余预算："+getMonthlyBudget());
    }

    private double calculateTotalIncome() {
        return incomeTransactions.stream()
                .mapToDouble(Transaction::getAmount)
                .sum();
    }
    private double calculateTotalExpenses() {
        return expenseTransactions.stream()
                .mapToDouble(Transaction::getAmount)
                .sum();
    }
    public void displayMothlyStatistics(){  //月度账单统计
        System.out.println("月度统计:"+"\n");
        System.out.println("总收入: " + calculateTotalIncome());
        System.out.println("总支出: " + calculateTotalExpenses());
        List<String> categories = expenseTransactions.stream()
                .map(Transaction::getCategory)
                .distinct()
                .collect(Collectors.toList());
        for (String category : categories) {
            double totalCategoryExpense = expenseTransactions.stream()
                    .filter(t -> t.getCategory().equals(category))
                    .mapToDouble(Transaction::getAmount)
                    .sum();
            System.out.println("类别 " + category + " 支出: " + totalCategoryExpense);
        }
    }

}


